<template>
  <div class="my-order-center-page">
    <!-- 顶部导航 -->
    <van-nav-bar 
      title="我的订单" 
      left-arrow 
      @click-left="goBack"
    />
    
    <!-- 视角切换 -->
    <div class="perspective-tabs">
      <div 
        class="tab-item"
        :class="{ active: currentPerspective === 'buyer' }"
        @click="switchPerspective('buyer')"
      >
        <van-icon name="shopping-cart-o" />
        <span>我买到的</span>
        <van-badge v-if="buyerStats.total > 0" :content="buyerStats.total" />
      </div>
      <div 
        class="tab-item"
        :class="{ active: currentPerspective === 'seller' }"
        @click="switchPerspective('seller')"
      >
        <van-icon name="home-o" />
        <span>我卖出的</span>
        <van-badge v-if="sellerStats.total > 0" :content="sellerStats.total" />
      </div>
    </div>
    
    <!-- 支付确认状态（买家和卖家视角统一） -->
    <div class="payment-status-section">
      <div class="stats-grid">
        <div class="stats-item" @click="filterOrders('pending')">
          <div class="stats-number">{{ currentPerspective === 'buyer' ? buyerStats.pending : sellerStats.pending }}</div>
          <div class="stats-label">待确认</div>
        </div>
        <div class="stats-item" @click="filterOrders('confirmed')">
          <div class="stats-number">{{ currentPerspective === 'buyer' ? buyerStats.completed : sellerStats.confirmed }}</div>
          <div class="stats-label">已确认</div>
        </div>
        <div class="stats-item" @click="filterOrders('rejected')">
          <div class="stats-number">{{ currentPerspective === 'buyer' ? buyerStats.cancelled : sellerStats.rejected }}</div>
          <div class="stats-label">已拒绝</div>
        </div>
      </div>
    </div>
    
    <!-- 订单列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="orders-section">
        <div class="section-title">
          {{ currentPerspective === 'buyer' ? '购买订单' : '销售订单' }}
          <span v-if="currentFilter !== 'all'" class="filter-tag">
            {{ getFilterText(currentFilter) }}
          </span>
        </div>
        
        <van-list
          v-model:loading="loading"
          :finished="!hasMore"
          finished-text="没有更多了"
          @load="loadMore"
        >
          <div 
            v-for="order in orderList" 
            :key="order.id" 
            class="order-item"
            @click="viewOrderDetail(order)"
          >
            <div class="order-main">
              <div class="order-info">
                <div class="product-info">
                  <img 
                    class="product-image" 
                    :src="order.product_image || order.productImage || 'https://via.placeholder.com/80x80'" 
                    alt="商品图片"
                  />
                  <div class="product-details">
                    <div class="product-title">{{ order.product_title || order.productTitle }}</div>
                    <div class="product-price">¥{{ formatPrice(order.amount || order.totalAmount) }}</div>
                  </div>
                </div>
                <div class="order-meta">
                  <div class="order-no">订单号：{{ order.order_no || order.orderNo }}</div>
                  <div class="order-time">{{ formatTime(order.create_time || order.createTime) }}</div>
                </div>
              </div>
              <div class="order-status">
                <div class="status-tag" :class="order.status">
                  {{ getStatusText(order.status, currentPerspective) }}
                </div>
                <div class="order-amount">¥{{ formatPrice(order.amount || order.totalAmount) }}</div>
              </div>
            </div>
            
            <!-- 操作按钮（仅卖家视角显示） -->
            <div v-if="order.status === 'pending' && currentPerspective === 'seller'" class="order-actions">
              <van-button 
                type="success" 
                size="small"
                @click.stop="confirmPayment(order)"
              >
                确认支付
              </van-button>
              <van-button 
                type="danger" 
                size="small"
                @click.stop="rejectPayment(order)"
              >
                拒绝支付
              </van-button>
            </div>
            
            <!-- 买家视角提示信息 -->
            <div v-if="order.status === 'pending' && currentPerspective === 'buyer'" class="buyer-pending-info">
              <van-icon name="info-o" color="#1989fa" />
              <span>支付凭证已上传，等待卖家确认</span>
            </div>
          </div>
        </van-list>
      </div>
    </van-pull-refresh>
    
    <!-- 空状态 -->
    <van-empty 
      v-if="!loading && orderList.length === 0"
      :description="currentPerspective === 'buyer' ? '暂无购买记录' : '暂无销售记录'"
      image="search"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { getPaymentList, getPaymentStats, confirmPayment as confirmPaymentApi, rejectPayment as rejectPaymentApi } from '@/api/payment-confirm'

const router = useRouter()

// 响应式数据
const currentPerspective = ref('buyer') // 'buyer' | 'seller'
const currentFilter = ref('all')
const orderList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(20)

// 买家订单状态（已移除，统一使用支付确认状态）

// 统计数据
const buyerStats = ref({
  total: 0,
  pending: 0,
  paid: 0,
  completed: 0,
  cancelled: 0
})

const sellerStats = ref({
  total: 0,
  pending: 0,
  confirmed: 0,
  rejected: 0
})

// 切换视角
const switchPerspective = (perspective) => {
  if (currentPerspective.value === perspective) return
  
  currentPerspective.value = perspective
  currentFilter.value = 'all'
  resetData()
  loadOrders()
  loadStats()
}

// 筛选订单
const filterOrders = (filter) => {
  if (currentFilter.value === filter) return
  
  currentFilter.value = filter
  resetData()
  loadOrders()
}

// 状态映射：前端状态值 -> 后端状态值（买家和卖家统一）
const getStatusMapping = (filter, perspective) => {
  if (filter === 'all') return ''
  
  // 买家和卖家使用相同的状态映射
  const statusMap = {
    'pending': 'pending',     // 待确认
    'confirmed': 'confirmed', // 已确认
    'rejected': 'rejected'    // 已拒绝
  }
  return statusMap[filter] || ''
}

// 重置数据
const resetData = () => {
  orderList.value = []
  page.value = 1
  hasMore.value = true
}

// 加载订单
const loadOrders = async (isRefresh = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    if (isRefresh) {
      page.value = 1
      hasMore.value = true
    }
    
    const currentPage = isRefresh ? 1 : page.value
    const mappedStatus = getStatusMapping(currentFilter.value, currentPerspective.value)
    const params = {
      page: currentPage,
      pageSize: pageSize.value,
      status: mappedStatus,
      perspective: currentPerspective.value
    }

    console.log('请求参数:', params)
    const response = await getPaymentList(params)
    console.log('订单列表响应:', response)

    // 处理后端返回的数据结构
    const newOrders = response.items || []
    console.log('处理后的列表数据:', newOrders)
    console.log('当前筛选状态:', currentFilter.value)
    console.log('映射后的状态:', mappedStatus)
    console.log('当前视角:', currentPerspective.value)
    
    if (isRefresh) {
      orderList.value = newOrders
      page.value = 1
      hasMore.value = (response.page || 0) < (response.total_page || 1) - 1
    } else {
      orderList.value = [...orderList.value, ...newOrders]
      page.value = currentPage + 1
      hasMore.value = (response.page || 0) < (response.total_page || 1) - 1
    }
    
    console.log('设置后的orderList:', orderList.value)
    
  } catch (error) {
    console.error('加载订单失败:', error)
    showToast('加载失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const stats = await getPaymentStats({ perspective: currentPerspective.value })
    console.log('统计数据响应:', stats)
    
    // 处理后端返回的统计数据结构
    const statsData = stats.data || {
      pending: 0,
      confirmed: 0,
      rejected: 0
    }
    
    if (currentPerspective.value === 'buyer') {
      // 买家统计
      buyerStats.value = {
        total: statsData.pending + statsData.confirmed + statsData.rejected,
        pending: statsData.pending,
        paid: statsData.pending, // 买家视角的"待确认"对应卖家的"待确认"
        completed: statsData.confirmed,
        cancelled: statsData.rejected
      }
    } else {
      // 卖家统计
      sellerStats.value = {
        total: statsData.pending + statsData.confirmed + statsData.rejected,
        pending: statsData.pending,
        confirmed: statsData.confirmed,
        rejected: statsData.rejected
      }
    }
  } catch (error) {
    console.error('加载统计失败:', error)
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value) return
  page.value++
  loadOrders()
}

// 下拉刷新
const onRefresh = () => {
  loadOrders(true)
  loadStats()
}

// 查看订单详情
const viewOrderDetail = (order) => {
  if (currentPerspective.value === 'buyer') {
    router.push({
      path: '/payment-detail',
      query: { 
        id: order.id,
        perspective: 'buyer'
      }
    })
  } else {
    router.push({
      path: '/payment-detail',
      query: { 
        id: order.id,
        perspective: 'seller'
      }
    })
  }
}

// 确认支付
const confirmPayment = async (order) => {
  try {
    const confirmed = await showConfirmDialog({
      title: '确认支付',
      message: '确认收到买家支付吗？'
    })
    
    if (confirmed) {
      await confirmPaymentApi(order.id, {
        order_id: order.id,
        action: 'confirm',
        remark: '卖家确认支付'
      })
      
      showToast('确认成功')
      loadOrders(true)
      loadStats()
    }
  } catch (error) {
    console.error('确认支付失败:', error)
    showToast('确认失败')
  }
}

// 拒绝支付
const rejectPayment = async (order) => {
  try {
    const confirmed = await showConfirmDialog({
      title: '拒绝支付',
      message: '确定要拒绝这个支付吗？'
    })
    
    if (confirmed) {
      await rejectPaymentApi(order.id, {
        order_id: order.id,
        action: 'reject',
        reject_reason: '卖家拒绝支付'
      })
      
      showToast('拒绝成功')
      loadOrders(true)
      loadStats()
    }
  } catch (error) {
    console.error('拒绝支付失败:', error)
    showToast('拒绝失败')
  }
}

// 获取状态文本（买家和卖家统一）
const getStatusText = (status, perspective) => {
  // 买家和卖家使用相同的状态文本
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 获取筛选文本（买家和卖家统一）
const getFilterText = (filter) => {
  // 买家和卖家使用相同的筛选文本
  const filterMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'rejected': '已拒绝'
  }
  return filterMap[filter] || filter
}

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  // 数据库中价格以元为单位存储，直接格式化
  return parseFloat(price).toFixed(2)
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 组件挂载
onMounted(() => {
  loadOrders()
  loadStats()
})
</script>

<style lang="scss" scoped>
.my-order-center-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.perspective-tabs {
  display: flex;
  background: #fff;
  margin-bottom: 10px;
  
  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px 10px;
    position: relative;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &.active {
      color: #1989fa;
      
      .van-icon {
        color: #1989fa;
      }
    }
    
    .van-icon {
      font-size: 24px;
      margin-bottom: 5px;
    }
    
    span {
      font-size: 14px;
      font-weight: 500;
    }
    
    .van-badge {
      position: absolute;
      top: 10px;
      right: 20px;
    }
  }
}

.order-status-section {
  background: #fff;
  margin-bottom: 10px;
  padding: 15px 0;
}

.payment-status-section {
  background: #fff;
  margin-bottom: 10px;
  padding: 20px;
  
  .stats-grid {
    display: flex;
    justify-content: space-around;
    
    .stats-item {
      text-align: center;
      cursor: pointer;
      padding: 10px;
      border-radius: 8px;
      transition: background-color 0.3s ease;
      
      &:hover {
        background-color: #f5f5f5;
      }
      
      .stats-number {
        font-size: 24px;
        font-weight: bold;
        color: #1989fa;
        margin-bottom: 5px;
      }
      
      .stats-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.orders-section {
  background: #fff;
  margin-bottom: 10px;
  
  .section-title {
    padding: 15px 20px;
    font-size: 16px;
    font-weight: 500;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    
    .filter-tag {
      margin-left: 10px;
      padding: 2px 8px;
      background: #1989fa;
      color: #fff;
      border-radius: 12px;
      font-size: 12px;
    }
  }
}

.order-item {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
  
  &:hover {
    background-color: #f9f9f9;
  }
  
  &:last-child {
    border-bottom: none;
  }
  
  .order-main {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
    
    .order-info {
      flex: 1;
      
      .product-info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        
        .product-image {
          width: 60px;
          height: 60px;
          border-radius: 8px;
          object-fit: cover;
          margin-right: 12px;
        }
        
        .product-details {
          flex: 1;
          
          .product-title {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .product-price {
            font-size: 16px;
            font-weight: bold;
            color: #ff4d4f;
          }
        }
      }
      
      .order-meta {
        .order-no {
          font-size: 12px;
          color: #999;
          margin-bottom: 3px;
        }
        
        .order-time {
          font-size: 12px;
          color: #999;
        }
      }
    }
    
    .order-status {
      text-align: right;
      
      .status-tag {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 5px;
        
        &.pending {
          background: #fff7e6;
          color: #fa8c16;
        }
        
        &.confirmed, &.completed {
          background: #f6ffed;
          color: #52c41a;
        }
        
        &.rejected {
          background: #fff2f0;
          color: #ff4d4f;
        }
      }
      
      .order-amount {
        font-size: 16px;
        font-weight: bold;
        color: #333;
      }
    }
  }
  
  .order-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    
    .van-button {
      border-radius: 20px;
      font-size: 12px;
      height: 32px;
      padding: 0 16px;
    }
  }
  
  .buyer-pending-info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 10px;
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 8px;
    color: #0369a1;
    font-size: 14px;
    margin-top: 10px;
    
    .van-icon {
      font-size: 16px;
    }
  }
}
</style>
